﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using FirstFloor.ModernUI.Windows.Controls;
using YanMsg.APCode;

namespace YanMsg.View
{
    /// <summary>
    /// ChatHistory.xaml 的交互逻辑
    /// </summary>
    public partial class ChatHistory : ModernWindow
    {
    
        public ChatHistory()
        {
            this.InitializeComponent();
            // 在此点之下插入创建对象所需的代码。
        }
        public ChatHistory(string strUserForm)
        {
            this.InitializeComponent();
            this.Style = (Style)App.Current.Resources["EmptyWindow"];

            this.RTBChatHistory.AppendText("正在加载历史记录，请稍后...");
            Task getMsgTask = new Task(() =>{
               this.Dispatcher.Invoke(new Action(() =>
               {
                   BindChatPeople(UserData.UserNumber, strUserForm);
                   GetHistoryMsg(strUserForm);
               }));
           });
           getMsgTask.Start();
        }





        //绑定聊天人
        public void BindChatPeople(string strUserTo, string strUserForm)
        {
            try
            {
                DataTable dtUser = new DataTable();
                dtUser = ChatHelp.GetChatUser(UserData.UserNumber);
                Dictionary<string, string> dic = new Dictionary<string, string>();
                for (int i = 0; i < dtUser.Rows.Count; i++)
                {
                    dic.Add(dtUser.Rows[i]["userfrom"].ToString(), UserData.ListPeople.Where(d => d.UserName == dtUser.Rows[i]["userfrom"].ToString()).SingleOrDefault().UserRealName);
                }
                CBXPeople.ItemsSource = dic;
                CBXPeople.SelectedValuePath = "Key";
                CBXPeople.DisplayMemberPath = "Value";
                CBXPeople.SelectedValue = strUserForm;
            }
            catch (Exception error)
            {
                MsgManger.Show(error.Message.ToString());
            }
        }



        private void CBXPeople_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.RTBChatHistory.Document.Blocks.Clear();
            this.RTBChatHistory.AppendText("正在加载历史记录，请稍后...");
            KeyValuePair<string, string> Item = (KeyValuePair<string, string>)CBXPeople.SelectedItem;
            Task getMsgTask = new Task(() =>
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    GetHistoryMsg(Item.Key.ToString());
                }));
            });
            getMsgTask.Start();
        }



        //删除历史
        private void imgDelChatHistory_MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = ModernDialog.ShowMessage("你确然要删除与该用户的对话?", "提示", MessageBoxButton.YesNo);
                
                //关闭窗口
                if (result.ToString() == "Yes")
                {
                    this.RTBChatHistory.Document.Blocks.Clear();
                    this.RTBChatHistory.AppendText("正在删除....");
                    Task delMsgTask = new Task(() =>
                    {
                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            
                            
                            KeyValuePair<string, string> strUserForm = (KeyValuePair<string, string>)CBXPeople.SelectedItem;

                            ChatHelp.delMsg(strUserForm.Key);
                            this.RTBChatHistory.Document.Blocks.Clear();
                            this.RTBChatHistory.AppendText("删除完毕");                    
                            
                        }));      
                    });           
                    delMsgTask.Start();  
                }      
            }
            catch (Exception error)
            {

                MsgManger.Show(error.Message.ToString());
            }
            
        }

        //获取记录
        private void GetHistoryMsg(string strUserForm)
        {
            try
            {
                imgDelChatHistory.IsEnabled = true;
                this.RTBChatHistory.Document.Blocks.Clear();
                List<YanChat_ChatHistory> ListMsg = new List<YanChat_ChatHistory>();
                ListMsg = ChatHelp.GetUserChatHis(strUserForm);
                foreach (var item in ListMsg)
                {
                    string msgConTent = ZipHelper.GZipDecompressString(item.mescontent);

                    //将信息加载到临时RichTextBox
                    System.Windows.Controls.RichTextBox RTemp = new System.Windows.Controls.RichTextBox();
                    ChatManger.LoadFromRTF(RTemp, msgConTent);

                    //添加信息头
                    string strMSTitle = ChatManger.GetUserName(item.userfrom) + "  " + DateTime.Parse(item.crdate.ToString()).ToString("yyyy-MM-dd HH:mm");
                    TextBlock TB = new TextBlock(new Bold(new Run(strMSTitle)));
                    if (item.userfrom == UserData.UserNumber)
                    {
                        TB.Foreground = new SolidColorBrush(Colors.Blue);
                    }
                    BlockUIContainer BU = new BlockUIContainer(TB);

                    this.RTBChatHistory.Document.Blocks.Add(BU);
                    //添加信息内容
                    for (int i = RTemp.Document.Blocks.Count - 1; i >= 0; i--)
                    {
                        var q = RTemp.Document.Blocks.ElementAt(i);
                        this.RTBChatHistory.Document.Blocks.Add(q);
                    }
                }
                if (ListMsg.Count()==0)
                {
                    imgDelChatHistory.IsEnabled = false;
                }
            }
            catch (Exception error)
            {
                MsgManger.Show("无法得到查询结果");
            }
        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }


    }
}